package com.dstats.fragments;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.adapter.NewsAdapter;
import com.dstats.R;
import com.dstats.SimpleWebView;
import com.entities.News;
import com.fetch.FetchXML;


public class NewsFragment extends Fragment {

	private ListView listView;
	private ProgressBar progressBarNewsFragment;
	private void setAdapterAndListener(List<News> list){
		if(list!=null){
			NewsAdapter news = new NewsAdapter(getActivity().getApplicationContext(), list);
			listView.invalidate();
			listView.setAdapter(news);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View view, int arg2,
						long arg3) {
					
					Intent intent = new Intent(getActivity(), SimpleWebView.class);
					intent.putExtra("url", ((News) adapter.getItemAtPosition(arg2)).getLink());
					startActivity(intent);
				}
				
			});
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.news_fragment, container, false);
		listView = (ListView) rootView.findViewById(R.id.listViewNews);
		progressBarNewsFragment = (ProgressBar) rootView.findViewById(R.id.progressBarNewsFragment);
		setAdapterAndListener(News.genNews.get(getString(R.string.blogFeed)));
		if(News.genNews.get(getString(R.string.blogFeed)) == null){
			new FetchNews().execute();
		}
		return rootView;
	}
	
	class FetchNews extends FetchXML{

		public FetchNews() {
			super(getString(R.string.blogFeed), News.tagName, News.fieldNames);
			
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBarNewsFragment.setVisibility(View.VISIBLE);
			progressBarNewsFragment.setIndeterminate(true);
		}
		
		@Override
		protected void onPostExecute(final List<List<String>> result) {
		
			super.onPostExecute(result);
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					
					setAdapterAndListener(News.getNewsBlog(result, getString(R.string.blogFeed)));
					progressBarNewsFragment.setVisibility(View.INVISIBLE);
					
				}
			});
		}
		
	}
}
